package com.hmdp.service.impl;

import cn.hutool.core.util.BooleanUtil;
import cn.hutool.core.util.StrUtil;
import cn.hutool.json.JSONUtil;
import com.baomidou.mybatisplus.extension.service.impl.ServiceImpl;
import com.hmdp.dto.Result;
import com.hmdp.entity.Shop;
import com.hmdp.mapper.ShopMapper;
import com.hmdp.service.IShopService;
import org.springframework.data.redis.core.StringRedisTemplate;
import org.springframework.stereotype.Service;
import org.springframework.transaction.annotation.Transactional;

import javax.annotation.Resource;
import java.util.concurrent.TimeUnit;

import static com.hmdp.utils.RedisConstants.*;

/**
 * <p>
 * 服务实现类
 * </p>
 *
 * @author 虎哥
 * @since 2021-12-22
 */
@Service
public class ShopServiceImpl extends ServiceImpl<ShopMapper, Shop> implements IShopService {

    @Resource
    private StringRedisTemplate stringRedisTemplate;

    @Override
    public Result queryById(Long id) {
        Shop shop = queryWithMutex(id);
        if (shop == null) {
            return Result.fail("为查询到数据");
        }
        return Result.ok(shop);
    }


    /**
     * 缓存击穿策略
     * 互斥锁
     * @param id
     * @return
     */
    public Shop queryWithMutex(Long id) {
        // 查询缓存
        String key = CACHE_SHOP_KEY + id;
        String shopJson = stringRedisTemplate.opsForValue().get(key);
        if (StrUtil.isNotBlank(shopJson)) {
            // 转为Java对象返回
            return JSONUtil.toBean(shopJson, Shop.class);
        }
        // 判断是否是NUll
        if (shopJson != null) {
            return null;
        }
        String lockKey = "lock:shop:" + id;
        Shop shop = null;
        try {
            if (tryLock(lockKey)) {
                // 再次判断缓存中是否存在数据（因为在获取锁的过程中可能其他线程已经放入缓存了）
                shopJson = stringRedisTemplate.opsForValue().get(key);
                if (StrUtil.isNotBlank(shopJson)) {
                    return JSONUtil.toBean(shopJson, Shop.class);
                }
                // 查询数据库
                shop = getById(id);
                if (shop == null) {
                    // 缓存null值 2分钟
                    stringRedisTemplate.opsForValue().set(key, "", CACHE_NULL_TTL, TimeUnit.MINUTES);
                    return null;
                }
                // 将Shop转为Json缓存到Redis中
                stringRedisTemplate.opsForValue().set(key, JSONUtil.toJsonStr(shop), CACHE_SHOP_TTL, TimeUnit.MINUTES);
            }else {
                Thread.sleep(50);
                return queryWithMutex(id);
            }
        } catch (Exception e) {
            throw new RuntimeException(e);
        } finally {
            unLock(lockKey);
        }
        return shop;
    }


    /**
     * 获取锁
     *
     * @param lockKey key
     * @return 是否枷锁成功
     */
    public boolean tryLock(String lockKey) {
        Boolean isLock = stringRedisTemplate.opsForValue().setIfAbsent(lockKey, Thread.currentThread().getId() + "", CACHE_SHOP_TTL, TimeUnit.SECONDS);
        return BooleanUtil.isTrue(isLock);
    }

    /**
     * 释放锁
     *
     * @param lockKey
     */
    private void unLock(String lockKey) {
        stringRedisTemplate.delete(lockKey);
    }

    /**
     * 缓存击穿问题
     * 缓存空对象
     *
     * @param id
     * @return
     */
    private Result getResult(Long id) {
        String Key = CACHE_SHOP_KEY + id;
        // 从Redis中查询数据
        String shopJson = stringRedisTemplate.opsForValue().get(Key);
        if (StrUtil.isNotBlank(shopJson)) {
            // 转为Java对象返回
            Shop shop = JSONUtil.toBean(shopJson, Shop.class);
            return Result.ok(shop);
        }
        // 从Mysql中查询数据
        Shop shop = getById(id);
        if (shop == null) {
            // 缓存NUll 2分钟
            stringRedisTemplate.opsForValue().set(Key, "", CACHE_NULL_TTL, TimeUnit.MINUTES);
            return Result.fail("店铺不存在~");
        }
        // 将Shop转Json缓存到Redis中
        stringRedisTemplate.opsForValue().set(Key, JSONUtil.toJsonStr(shop), CACHE_SHOP_TTL, TimeUnit.MINUTES);
        return Result.ok(shop);
    }

    @Override
    @Transactional
//    TODO 压测
    public Result updateShop(Shop shop) {
        if (shop.getId() == null) {
            return Result.fail("店铺Id不能为空~");
        }
        // 先删缓存
        stringRedisTemplate.delete(CACHE_SHOP_KEY + shop.getId());
        updateById(shop);
        return Result.ok();
    }
}
